package com.lxj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxj.anno.Log;
import com.lxj.domain.SysUser;
import com.lxj.mapper.SysUserMapper;
import com.lxj.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author lxj
 * @date 2021/7/31 12:11
 * @Description:
 */
@RestController
@RequestMapping("sys/user")
@Api(tags = "后台用户管理")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("info")
    @ApiOperation("查询当前登录的用户信息")
    public ResponseEntity<SysUser> userInfo(){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getById(userId);
        return ResponseEntity.ok(sysUser);
    }

    @GetMapping("page")
    @ApiOperation("分页查询管理员列表")
    @PreAuthorize("hasAuthority('sys:user:page')")
    @Log(operation = "分页查询管理员列表")
    public ResponseEntity<Page<SysUser>> loadSysUserPage(Page<SysUser> page, SysUser sysUser){
        Page<SysUser> sysUserPage = sysUserService.loadSysUserPage(page, sysUser);
        return ResponseEntity.ok(sysUserPage);
    }

    @PostMapping
    @ApiOperation("新增管理员")
    @Log(operation = "新增管理员")
    public ResponseEntity<Void> addSysUser(@RequestBody SysUser sysUser) {
        // 拿到当前用户
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        sysUser.setCreateUserId(Long.valueOf(userId));
        sysUserService.save(sysUser);
        return ResponseEntity.ok().build();
    }
}
